<template>
  <div>
    <el-container style="padding: 0">
      <el-main style="padding: 0">
        <el-container v-show="listFlag" style="flex-direction: column;">
          <el-header style="height: 40px;">
            <el-button @click="listFlag = false">新建群发消息</el-button>
            <el-button @click="getList">刷新列表</el-button>
          </el-header>
          <el-main style="min-height: 300px;">

            <el-table :data="tableData" style="width: 100%" border>
              <el-table-column type="index" label="序号" width="60"/>
              <el-table-column prop="message" label="消息" width="250">
                <template #default="scope">
                  {{computeMessage(scope.row)}}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                  {{ computedStatus(scope.row.status) }}
                </template>
              </el-table-column>
              <el-table-column prop="sendtime" label="群发时间" width="160"/>
              <el-table-column prop="msgType" label="消息类型" width="120">
                <template #default="scope">
                  {{ computedMsgType(scope.row.msgType) }}
                </template>
              </el-table-column>
              <el-table-column prop="groupName" label="发送对象" width="120"/>
              <el-table-column prop="address" label="操作">
                <template #default="scope">
                  <el-button
                      type="text"
                      icon="Edit"
                      @click="handleUpdate(scope.row)"
                  >重新发送
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-main>

          <div class="page-div">
            <el-pagination
                v-show="total>0"
                v-model:currentPage="queryParams.pageNum"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[10,20,30,50]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </el-container>
        <el-container v-show="!listFlag" style="flex-direction: column;">
          <el-header style="height: 40px; display: flex; align-items: center;justify-content: space-between;">
            <div style="display: flex; align-items: center;">
              <span>群发消息</span>
              <el-select style="margin-left: 15px;" v-model="selectValue" @change="groupSelected">
                <el-option value="1" label="全部用户"/>
                <el-option value="2" label="按分组选择"/>
              </el-select>

              <el-select v-if="showList" style="margin-left: 15px;" v-model="selectGroupValue">
                    <el-option v-for="(item,index) in groupData" :label="item.name" :value="index" />
              </el-select>
            </div>
            <el-button @click="listFlag=true" type="primary">返回列表</el-button>
          </el-header>
          <el-main>
            <el-tabs  type="border-card" v-model="selectBorderValue" @tab-click="tabClick">
              <el-tab-pane label="文字消息" name="1">
                <template #label>
                  <el-icon>
                    <EditPen/>
                  </el-icon>
                  <span style="margin-left: 5px;">文字消息</span>
                </template>
                <el-input
                    v-model="textContext"
                    maxlength="600"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    show-word-limit
                    placeholder="请输入"
                />
              </el-tab-pane>
              <el-tab-pane label="语音消息" name="2">
                <template #label>
                  <el-icon>
                    <Microphone/>
                  </el-icon>
                  <span style="margin-left: 5px;">语音消息</span>
                </template>
                <el-input
                    v-model="textContext"
                    maxlength="600"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    show-word-limit
                    placeholder="请输入"
                />
              </el-tab-pane>
              <el-tab-pane label="图片消息" name="3">
                <template #label>
                  <el-icon>
                    <PictureFilled/>
                  </el-icon>
                  <span style="margin-left: 5px;">图片消息</span>
                </template>
                <el-input
                    v-model="textContext"
                    maxlength="600"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    show-word-limit
                    placeholder="请输入"
                />
              </el-tab-pane>
              <el-tab-pane label="视频消息" name="4">
                <template #label>
                  <el-icon>
                    <VideoCameraFilled/>
                  </el-icon>
                  <span style="margin-left: 5px;">视频消息</span>
                </template>
                <el-input
                    v-model="textContext"
                    maxlength="600"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    show-word-limit
                    placeholder="请输入"
                />
              </el-tab-pane>

              <el-tab-pane label="图文消息" name="5">
                <template #label>
                  <el-icon>
                    <Ticket/>
                  </el-icon>
                  <span style="margin-left: 5px;">图文消息</span>
                </template>
                <el-input
                    :disabled="disabled"
                    v-model="textContext"
                    maxlength="600"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    show-word-limit
                    placeholder="请选择图文消息"
                />
              </el-tab-pane>
            </el-tabs>
          </el-main>
          <el-footer>
            <el-button type="primary" @click="save">确定发送</el-button>
            <el-button @click="dingshi">定时发送</el-button>
          </el-footer>
        </el-container>
      </el-main>
      <el-aside width="260px">
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="vertical"
            @select="handleSelect"
        >
          <el-menu-item index="1">全部发送</el-menu-item>
          <el-menu-item index="2">已发送</el-menu-item>
          <el-menu-item index="3">定时发送</el-menu-item>
        </el-menu>
      </el-aside>
    </el-container>

    <el-dialog
        v-model="dialogVisible"
        title="定时发送"
        width="30%"
        :center="true"
        :before-close="handleClose"
    >
      <div style="display: flex;align-items: center;justify-content: center;">
        <el-date-picker
            v-model="selectDateTime"
            type="datetime"
            placeholder="请选择发送时间"
            format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disableDate"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSend"
          >确认</el-button
          >
        </span>
      </template>
    </el-dialog>


    <el-dialog
        v-model="tuwenDialog"
        title="请选择图文"
        width="50%"
        :before-close="handleClose"
    >
      <el-table :data="tuwenDate" style="width: 100%" border>
        <el-table-column type="index" label="ID" width="100">
              <template #default="scope">
                <el-radio v-model="currentSelect" :label="scope.row.id" >{{scope.row.id}}</el-radio>
              </template>
        </el-table-column>
        <el-table-column prop="title" label="名称" width="180"/>
        <el-table-column prop="creationTime" label="创建时间" width="180"/>
        <el-table-column prop="type" label="图文类型" width="180">
          <template #default="scope">
            {{scope.row.type ===0?'单图文':'多图文'}}
          </template>
        </el-table-column>
      </el-table>
      <div class="page-div">
        <el-pagination
            v-show="total1>0"
            v-model:currentPage="queryParams2.pageNum"
            v-model:page-size="queryParams2.pageSize"
            :page-sizes="[10,20,30,50]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
        />
      </div>


      <template #footer>
            <span class="dialog-footer">
              <el-button @click="tuwenDialog = false">取消</el-button>
              <el-button type="primary" @click="selectImageConfirm"
              >确认</el-button
              >
            </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="groupsend" lang="ts">
import {listImagetext} from '/@/api/publicaccount/imagetext'
import {computed, onMounted, reactive, ref, toRefs} from "vue";
import {listMsgpub, addMsgpub, updateMsgpub} from '/@/api/publicaccount/msgpub'
import usePublicAccount from '/@/stores/modules/publicaccount'
import {parseTime} from '/@/utils/timeutils'
import {ElMessage, TabsPaneContext} from "element-plus";
import {listGroup,addGroup,updateGroup,delGroup} from  '/@/api/publicaccount/group'

const currentSelect = ref();
const groupData = ref([]);
function getGroup(){
  const query = {
    pusername: publicAccount.selectid,
  }
  listGroup(query).then(rep =>{
    groupData.value = rep.rows;
  });
}

const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

function getImageList() {
  loading.value = true;
  listImagetext(queryParams2).then(response => {
    tuwenDate.value = response.rows;
    total1.value = response.total;
    loading.value = false;
  });
}

const publicAccount = usePublicAccount();
const total = ref(0);
const total1 = ref(0);

const loading = ref(true);
const activeIndex = ref('1')
const tableData = ref([]);
const tuwenDate = ref([]);

const pageNum = ref(1);
const pageSize = ref(10);

const pageNum2= ref(1);
const pageSize2 = ref(10);

const queryParams = reactive({
  pageNum: pageNum.value,
  pageSize: pageSize.value,
  fromuser: publicAccount.selectid,
});

const queryParams2 = reactive({
  pageNum: pageNum2.value,
  pageSize: pageSize2.value,
  fromuser: publicAccount.selectid,
});

const computeMessage = computed(()=>(item)=>{
     if(item.msgType === 0){
        return item.message;
     }else{
        let newMessage= JSON.parse(item.message);
        return  newMessage.title;
     }
})

const computedStatus = computed(() => (status: any) => {
  if (status === 1) {
    return '正在发送';
  }
  if (status === 2) {
    return '已发送';
  }

  if (status === 3) {
    return '取消发送'
  }
  if (status === 4) {
    return '已删除； 民，核聚变。、‘’'
  }
  return '未知的状态';
});

const computedMsgType = computed(() => (msgType: any) => {
  if (msgType === 0) {
    return '文字消息';
  }
  if (msgType === 1) {
    return '图文消息';
  }

  if (msgType === 2) {
    return '取消发送'
  }
  if (msgType === 3) {
    return '已删除'
  }
  return '未知的状态';
});

onMounted(() => {
  getList();
  getGroup();
})

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList()
}

const handleSizeChange2 = (val: number) => {
  pageSize2.value = val;
  getImageList()
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  getList()
}

const handleCurrentChange2 = (val: number) => {
  pageNum2.value = val;
  getImageList()
}

function groupSelected() {
    console.info("selectValue：",selectValue.value);
    getGroup();
    if(selectValue.value == 2){
       showList.value =true;
    }else{
      showList.value =false;
    }
}

function getList() {
  loading.value = true;
  listMsgpub(queryParams).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function save() {
  let data = {};
  if (textContext.value === '') {
    ElMessage.error('请输入发送内容');
    return;
  }
  console.info("selectDateTime.value:",selectDateTime.value);
  if(selectBorderValue.value === '5'){
      const findResult= tuwenDate.value.find(item => {
        if(item.id === currentSelect.value){
          return item;
        }
      })
      console.info("findResult",findResult);

      data = {
        fromuser: publicAccount.selectid,
        msgType: 1,
        touser: selectValue.value == 1 ? 'ALL' : groupData.value[selectGroupValue.value].id,
        groupName: selectValue.value == 1 ? '全部用户' : groupData.value[selectGroupValue.value].name,
        message: JSON.stringify(findResult),
        status: 1,
        touserType: 4,
        sendtime: selectDateTime.value !== null?  parseTime(selectDateTime.value) :parseTime(new Date()),
        createTime: parseTime(new Date())
      };
  }

  if(selectBorderValue.value === '1') {
    data = {
      fromuser: publicAccount.selectid,
      msgType: 0,
      touser: selectValue.value == 1 ? 'ALL' : groupData.value[selectGroupValue.value].id,
      groupName: selectValue.value == 1 ? '全部用户' : groupData.value[selectGroupValue.value].name,
      message: textContext.value,
      status: 1,
      touserType: 4,
      sendtime: selectDateTime.value !== null ?  parseTime(selectDateTime.value) :parseTime(new Date()),
      createTime: parseTime(new Date())
    };
  }
  addMsgpub(data).then((result) => {
    console.info("Result", result);
    getList();
    listFlag.value = true;
    textContext.value = '';
  });
}

function confirmSend(){
  let data = {};
  if (textContext.value === '') {
    ElMessage.error('请输入发送内容');
    return;
  }
  if(selectBorderValue.value === '5'){
    const findResult= tuwenDate.value.find(item => {
      if(item.id === currentSelect.value){
        return item;
      }
    })
    console.info("findResult",findResult);

    data = {
      fromuser: publicAccount.selectid,
      msgType: 1,
      touser: selectValue.value == 1 ? 'ALL' : groupData.value[selectGroupValue.value].id,
      groupName: selectValue.value == 1 ? '全部用户' : groupData.value[selectGroupValue.value].name,
      message: JSON.stringify(findResult),
      status: 1,
      touserType: 4,
      sendtime: selectDateTime.value !== null?  parseTime(selectDateTime.value) :parseTime(new Date()),
      createTime: parseTime(new Date())
    };
  }

  if(selectBorderValue.value === '1') {
    data = {
      fromuser: publicAccount.selectid,
      msgType: 0,
      touser: selectValue.value == 1 ? 'ALL' : groupData.value[selectGroupValue.value].id,
      groupName: selectValue.value == 1 ? '全部用户' : groupData.value[selectGroupValue.value].name,
      message: textContext.value,
      status: 1,
      touserType: 4,
      sendtime: selectDateTime.value !== null?  parseTime(selectDateTime.value) :parseTime(new Date()),
      createTime: parseTime(new Date())
    };
  }
  addMsgpub(data).then((result) => {
    dialogVisible.value = false;
    console.info("Result", result);
    getList();
    listFlag.value = true;
    textContext.value = '';
    selectDateTime.value = null;
  });

}

function selectImageConfirm(){
    const findResult= tuwenDate.value.find(item => {
        if(item.id === currentSelect.value){
          return item;
        }
    })
    console.info("findResult",findResult);
    if(findResult){
       textContext.value = findResult.title;
    }
    inputDisabled.value = true;
    tuwenDialog.value=false;
}


function handleClose() {
  dialogVisible.value = false;
  tuwenDialog.value=false;
}

function disableDate(date) {
  if (date.getTime() >= (new Date().getTime()-24*60*60*1000)) {
    return false;
  } else {
    return true;
  }
}

function dingshi() {
  if (textContext.value.trim() === '') {
    ElMessage({
      message: '请输入发送内容',
      type: 'warning',
    })
    return;
  }
  dialogVisible.value = true;
}

function handleUpdate(item) {
  console.info("item", item);
  item.status = 1;
  updateMsgpub(item).then(resp => {
    console.info(resp);
    getList();
  })
}

const tabClick = (tab: TabsPaneContext, event: Event) => {
   if(selectBorderValue.value === '5'){
          tuwenDialog.value=true;
          getImageList();
   }
}

const inputDisabled = ref(false);
const selectBorderValue = ref("1");
const tuwenDialog = ref(false);
const selectGroupValue = ref(0);
const showList = ref(false);
const dialogVisible = ref(false);
const selectDateTime = ref(null);
const selectValue = ref("1");
const listFlag = ref(true);
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const textContext = ref("");
</script>

<style scoped lang="scss">
.page-div {
  margin-top: 20px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
